from app.core.helpers import hash_password, verify_password
from app.core.responses import Response
from schemas.auth import VerificationRequest, VerificationSubmit, SettingPassword, UserLogin
from app.services.auth import *
from fastapi import APIRouter
from app.models.Users import Users
from app.models.VerificationCodes import VerificationCodes

router = APIRouter(prefix="/auth")


# @router.post("/wechat")
# async def wechat_auth(request: Request, auth: WechatAuth):
#     app = WeChatService()
#     oauth = app.oauth().code_to_session(auth.code)
#     if not oauth:
#         raise ApiException("code error")
#     user = Users.where('openid', '=', oauth['openid']).get().serialize()
#     if not user:
#         user = UserService.create_user(openid=oauth['openid']).serialize()
#     else:
#         user = user[0]
#     # 过期时间
#     access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
#     # 把id进行username加密，要使用str类型
#     jwt_data = {
#         "user_id": user['id'],
#     }
#     access_token = create_access_token(
#         data={"sub": jwt_data}, expires_delta=access_token_expires
#     )
#     user['token'] = access_token
#     return Response.success(data=UserBase(**user))


@router.post("/user_info",summary="获取用户信息")
async def wechat_auth(user:str = Depends(get_current_user)):
    return Response.success(user)


@router.post("/verification_code",summary="发送验证码")
async def request_verification(request: VerificationRequest):
    is_login = request.is_login
    # 验证注册
    if not is_login:
        if Users.where('phone', request.phone).where('is_active',True).first():
            return Response.failed(message="手机号已注册")

    user = Users.where('phone', request.phone).first()
    if not user:
        user = Users.create(phone=request.phone, is_active=False)
    code = 123456
    expires_at = datetime.utcnow() + timedelta(minutes=5)
    VerificationCodes.create(user_id=user.id, code=code, expires_at=expires_at,type='sms')
    # TODO: Send SMS with verification code
    return {"message": "已发送验证码"}


@router.post("/verify", summary="验证码注册")
async def verify(verification: VerificationSubmit):
    user = Users.where('phone', verification.phone).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    valid_code = VerificationCodes.where('user_id', user.id) \
        .where('code', verification.code) \
        .where('is_used', False) \
        .where('expires_at', '>', datetime.utcnow()) \
        .first()

    if not valid_code:
        raise HTTPException(status_code=400, detail="验证码错误或已过期")
    valid_code.is_used = True
    valid_code.save()
    user.is_active = True
    user.save()
    access_token = create_access_token(data={"sub": user.id})
    return {"access_token": access_token, "token_type": "bearer"}


@router.post("/setting_password",summary="设置密码")
async def setting_password(request: SettingPassword,user:str = Depends(check_jwt_token)):
    if request.password != request.verify_password:
        return Response.failed(message="两次密码不一致")
    user = Users.find(user['id'])
    user.password_hash = hash_password(request.password)
    user.save()
    return Response.message('设置密码成功！')


@router.post("/login",summary="账号登录")
async def login(request: UserLogin):
    db_user = Users.where('phone', request.phone).first()
    if not db_user or not verify_password(request.password, db_user.password_hash):
        raise HTTPException(status_code=400, detail="手机或密码不正确")
    access_token = create_access_token(data={"sub": db_user.id})
    return {"access_token": access_token, "token_type": "bearer"}


